var oTableCategories;

var server_path;
var server_path_shop;
var category_id;
var map;
  var marker
var selected_theme='x52';
var selected_color_scheme='';
var string_custom_colors;
var langs;
 function initialize() {
 	mylatlang =new google.maps.LatLng(44.5403, -78.5463);
    var mapCanvas = document.getElementById('map_canvas');
    var mapOptions = {
      center: mylatlang,
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    } 
	
  map = new google.maps.Map(map_canvas, mapOptions);
  marker = new google.maps.Marker({
	      position: mylatlang,
	      map: map,
	      title: 'My shop address!'
	  });
  google.maps.event.addListener(map, "click", function(event)
{
                // place a marker
   placeMarker(event.latLng);
});

  }
//place marker function
function placeMarker(location) {

            marker.setPosition(location);
        }

$(document).ready(function(){	
server_path_shop = $("#server_path_shop").val();
server_path = "http:/www.neo-flux.com/wizard/";


// function for rte 
	$('.wysiwyg-editor').ace_wysiwyg({
		toolbar:
		[
			'font',
			null,
			'fontSize',
			null,
			{name:'bold', className:'btn-info'},
			{name:'italic', className:'btn-info'},
			null,
			{name:'underline', className:'btn-info'},
			null,
			null,
			null,
			null,
			null,
			null,
			{name:'justifyleft', className:'btn-primary'},
			null,
			null,
			{name:'justifyfull', className:'btn-inverse'},
			null,
			null,
			null,
			null,
			null,
			null,
			'foreColor',
			null,
			null,
			null,
		],
		'wysiwyg': {
			// fileUploadError: showErrorAlert
		}
	}).prev().addClass('wysiwyg-style2');



//for color pickers
$('.colorpicker1').colorpicker();
$('.colorpicker').css('z-index','20000000000');
// initialize google maps
	initialize();
//mask for telephone number 
	$('.input-mask-phone').mask('(999) 999-9999');

// logo upload
	$('#id-input-file-3').ace_file_input({
					style:'well',
					btn_choose:'Drop files here or click to choose',
					btn_change:null,
					no_icon:'icon-cloud-upload',
					droppable:true,
					thumbnail:'small'
					,icon_remove:null//set null, to hide remove/reset button
					,before_change:function(files, dropped) {
						//Check an example below
						//or examples/file-upload.html
						// console.log(files);
						// alert($('#id-input-file-3').val());
						return true;
					}
					,before_remove : function() {
						// alert('aaaa');
						return true;
					}
					,
					preview_error : function(filename, error_code) {
						//name of the file that failed
						//error_code values
						//1 = 'FILE_LOAD_FAILED',
						//2 = 'IMAGE_LOAD_FAILED',
						//3 = 'THUMBNAIL_FAILED'
						//alert(error_code);
						// alert(error_code);
						// alert(filename);
					}
			
				}).on('change', function(){
					// console.log($(this).data('ace_input_files'));
					// console.log($(this).data('ace_input_method'));
				});
		$('#id-file-format').removeAttr('checked').on('change', function() {
					var before_change
					var btn_choose
					var no_icon
					if(this.checked) {
						btn_choose = "Drop images here or click to choose";
						no_icon = "icon-picture";
						before_change = function(files, dropped) {
							var allowed_files = [];
							for(var i = 0 ; i < files.length; i++) {
								var file = files[i];
								if(typeof file === "string") {
									//IE8 and browsers that don't support File Object
									if(! (/\.(jpe?g|png|gif|bmp)$/i).test(file) ) return false;
								}
								else {
									var type = $.trim(file.type);
									if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif|bmp)$/i).test(type) )
											|| ( type.length == 0 && ! (/\.(jpe?g|png|gif|bmp)$/i).test(file.name) )//for android's default browser which gives an empty string for file.type
										) continue;//not an image so don't keep this file
								}
								
								allowed_files.push(file);
							}
							if(allowed_files.length == 0) return false;
			
							return allowed_files;
						}
					}
					else {
						btn_choose = "Drop files here or click to choose";
						no_icon = "icon-cloud-upload";
						before_change = function(files, dropped) {
							return files;
						}
					}
					var file_input = $('#id-input-file-3');
					file_input.ace_file_input('update_settings', {'before_change':before_change, 'btn_choose': btn_choose, 'no_icon':no_icon})
					file_input.ace_file_input('reset_input');
				});
// for carousel
	$("#owl-pick").owlCarousel({

		navigation : true, // Show next and prev buttons
		slideSpeed : 300,
		paginationSpeed : 400,
		singleItem:false,
		pagination:false,
		 items : 2,
		navigationText:[ "<i class='icon-chevron-left icon-white'></i>","<i class='icon-chevron-right icon-white'></i>"]

		// "singleItem:true" is a shortcut for:
		// items : 1,
		// itemsDesktop : false,
		// itemsDesktopSmall : false,
		// itemsTablet: false,
		// itemsMobile : false

	});
	// $("#owl-header").owlCarousel({

	// 	navigation : true, // Show next and prev buttons
	// 	slideSpeed : 300,
	// 	paginationSpeed : 400,
	// 	singleItem:false,
	// 	pagination:false,
	// 	navigationText:[ "<i class='icon-chevron-left icon-white'></i>","<i class='icon-chevron-right icon-white'></i>"]

	// 	// "singleItem:true" is a shortcut for:
	// 	// items : 1,
	// 	// itemsDesktop : false,
	// 	// itemsDesktopSmall : false,
	// 	// itemsTablet: false,
	// 	// itemsMobile : false

	// });
	// $("#owl-footer").owlCarousel({

	// 	navigation : true, // Show next and prev buttons
	// 	slideSpeed : 300,
	// 	paginationSpeed : 400,
	// 	singleItem:false,
	// 	pagination:false,
	// 	navigationText:[ "<i class='icon-chevron-left icon-white'></i>","<i class='icon-chevron-right icon-white'></i>"]
	// 	// "singleItem:true" is a shortcut for:
	// 	// items : 1,
	// 	// itemsDesktop : false,
	// 	// itemsDesktopSmall : false,
	// 	// itemsTablet: false,
	// 	// itemsMobile : false

	// });
	$("#owl-prodlist").owlCarousel({

		navigation : true, // Show next and prev buttons
		slideSpeed : 300,
		paginationSpeed : 400,
		singleItem:false,
		pagination:false,
		items : 2,
		navigationText:[ "<i class='icon-chevron-left icon-white'></i>","<i class='icon-chevron-right icon-white'></i>"]
		// "singleItem:true" is a shortcut for:
		// items : 1,
		// itemsDesktop : false,
		// itemsDesktopSmall : false,
		// itemsTablet: false,
		// itemsMobile : false

	});
	$("#owl-product").owlCarousel({

		navigation : true, // Show next and prev buttons
		slideSpeed : 300,
		paginationSpeed : 400,
		singleItem:false,
		pagination:false,
		items : 2,
		navigationText:[ "<i class='icon-chevron-left icon-white'></i>","<i class='icon-chevron-right icon-white'></i>"]
		// "singleItem:true" is a shortcut for:
		// items : 1,
		// itemsDesktop : false,
		// itemsDesktopSmall : false,
		// itemsTablet: false,
		// itemsMobile : false

	});

	$(function() {

		$('[data-rel=tooltip]').tooltip();



		var $validation =false ;
		$('#fuelux-wizard').ace_wizard().on('change' , function(e, info){			
			$validation = $("#wizard_form").valid();
			$("#preview_page").val(info.step);
			if(info.step == 2 && !$validation) {
				return false;
			}
			else if(info.step == 2){

				var lat = marker.getPosition().lat();
				var lng = marker.getPosition().lng();
				string = lat+', '+lng;
				langs='';
				$('input[type=checkbox][name=languages]').each(function(){
					if($(this).is(':checked')){
					langs=langs+$(this).val()+',';}
				});


				var sendData = [];
				sendData.push({name: 'site_name', value: $("#site_name").val() });
				sendData.push({name: 'domain_name', value: $("#domain_name").val() });
				sendData.push({name: 'email_contact', value: $("#email_contact").val() });
				sendData.push({name: 'telephone', value: $("#telephone").val() });
				sendData.push({name: 'address', value: $("#address").val() });
				sendData.push({name: 'site_category', value: $("#site_category").val() });
				sendData.push({name: 'languages', value: langs });
				sendData.push({name: 'state', value: $("#state").val() });
				sendData.push({name: 'city', value: $("#city").val() });
				sendData.push({name: 'zip_code', value: $("#zip_code").val() });
				sendData.push({name: 'map_marker', value: string });
				
				// console.log(dataSend);
				
				$.ajax({
					type: "POST",
					url: "http://www.neo-flux.com/wizard/libs/generate-shop_ajax.php",
					data: sendData,
					// dataType:'json',
					success: function(data){	
						close_spiner();					
						// $("#preview_page").show();
						// insert = "<span class='control-label'>"+$("#site_name").val()+"</span>";
						// $(insert).insertAfter("#site_name");
						$("#site_name").attr('readonly','readonly');
					}
				});
				array_lang=langs.split(",")
				$.each( array_lang, function( key, value ) {
					$("li#lng_"+value).removeClass('hide');
				});
				$("#myTab li.hide").css('display','none');
				$("#myTab li:not(.hide):first").trigger('click');
			



			}else if(info.step == 3){
				open_spiner();
				dataString = 'update_theme='+selected_theme;
				$.ajax({
					type: "POST",
					url: "http://www.neo-flux.com/wizard/libs/generate-shop_ajax.php",
					data: dataString,
					// dataType:'json',
					success: function(data){	
						$("#color_scheme_wrapper").html(data);
						$('[data-rel=tooltip]').tooltip();
													
					}
				});
			}else if(info.step == 4){
				open_spiner();
				if(selected_color_scheme=='custom_color_scheme'){
					dataSend = 'save_custom_color_scheme='+string_custom_colors;
				}else{
					dataSend = 'save_color_scheme='+selected_color_scheme;
				}
				$.ajax({
					type: "POST",
					url: "http://www.neo-flux.com/wizard/libs/generate-shop_ajax.php",
					data: dataSend,
					// dataType:'json',
					success: function(data){						
						close_spiner();	
					}
				});
				
			}	
			else if(info.step==5){
				// open_spiner();
				// dataSend='get_table_categories=1';
				// $.ajax({
				// 	type: "POST",
				// 	url: server_path+"wizard/libs/generate-shop_ajax.php",
				// 	data: dataSend,
				// 	// dataType:'json',
				// 	success: function(data){
				// 		close_spiner();				
				// 		$('#table_categories_wrapper').html(data);
				// 		oTableCategories = $('#sample-table-2').dataTable( {
				// 			"aoColumns": [
				// 			{ "bSortable": true },
				// 			true, false,
				// 			{ "bSortable": false }
				// 			] } );
				// 		$(".dataTables_paginate ul li").css('display','inline');
				// 	}
				// });

			 }
			// else if(info.step == 6){
			// 	dataSend = $("#wizard_steps").serialize()+'&update_shop=1';
			// 	// alert(dataSend);
			// 	$.ajax({
			// 		type: "POST",
			// 		url: server_path+"wizard/libs/generate-shop_ajax.php",
			// 		data: dataSend,
			// 		// dataType:'json',
			// 		success: function(data){						
						
			// 		}
			// 	});
			// }
		}).on('finished', function(e) {
			// dataSend = $("#wizard_form").serialize();


			bootbox.dialog("Va multumim! Informatiile tale au fost salvate si poti accesa site-eu la linkul <a href='shop.neo-flux.com'>shop.neo-flux.com</a>.<br />Da click pe ok si continua spre pagina produselor.", [{
				"label" : "OK",
				"class" : "btn-small btn-primary",
				callback: function() {
					window.location.assign("http://www.neo-flux.com/wizard/profile.html");
				},
			}]
			);
		}).on('stepclick', function(e){
		//return false;//prevent clicking on steps
	});			


		$('#modal-wizard .modal-header').ace_wizard();
		$('#modal-wizard .wizard-actions .btn[data-dismiss=modal]').removeAttr('disabled');
		




	})
var oTable1 = $('#sample-table-2').dataTable( {
	"aoColumns": [
	{ "bSortable": true },
	null,
	{ "bSortable": false }
	] } );
$("#dataTables_paginate ul li").css('display','inline');



});

$(function() {


	$(".chzn-select").chosen().on('change', function(){
		$(this).closest('form').validate().element($(this));
	}); 
	$(".chzn-container").css('width','100%');
	


	$('#wizard_form').validate({
		errorElement: 'span',
		errorClass: 'help-inline red',
		focusInvalid: true,
		rules: {
			site_category: {
				required: true
			},
			email_contact: {
				required: true,
				email:true
			},
			site_name: {
				required: true
			},
			domain_name: {
				required: true
			},
			languages: {
				required: true
			},
			telephone: {
				required: true
			},
			address: {
				required: true
			}
			
		},
		messages: {
			email_contact: {
				required: "Please provide a valid email.",
				email: "Please provide a valid email."
			},
			domain_name: {
				required: "Please specify a domain for your shop."
			},
			site_name: {
				required: "Please specify a shop name."
			},
			site_category: {
				required:"Please choose at least one category"
			},
			languages: {
				required:"Please choose at least one language"
			} ,
			telephone: {
				required:"Please specify a telephone number"
			},
			address: {
				required:"Please specify a address"
			}
			
		},

					invalidHandler: function (event, validator) { //display error alert on form submit   
						$('.alert-error', $('#wizard_form')).show();
					},

					highlight: function (e) {
						
						$(e).closest('div.control-group').removeClass('info').addClass('error');
					},

					success: function (e) {					
						$(e).closest('.control-group').removeClass('error').addClass('info');
						$(e).remove();
					},

					errorPlacement: function (error, element) {
						console.log(element);
						if(element.is(':checkbox') || element.is(':radio')) {
							var controls = element.closest('.controls');
							if(controls.find(':checkbox,:radio').length > 1) controls.append(error);
							else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
						}
						else if(element.is('.select2')) {
							error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
						}
						else 
							if(element.is('.chzn-select')) {
								error.insertAfter(element.siblings('[class*="chzn-container"]:eq(0)'));
							}
							else error.insertAfter(element);
						},

						submitHandler: function (form) {
						},
						invalidHandler: function (form) {
						}

					});


});
$(".preview_page").on('click',function(){
	if(this.value==1){
		url ="http://www.shop.neo-flux.com/";
	}else if(this.value==2){
			url ="http://www.shop.neo-flux.com/";
	}
	else if(this.value==3){
		var str=langs;
		
		var res = str.split(",");
		
		lang =  res[0].toLowerCase();
		
		url =server_path_shop+"shop/"+lang+"/category-"+lang+"1/";
	}
	else if(this.value==4){
		
		
		url =server_path_shop+"ro/category-ro1/produs.html";
	}
	window.open(url,'_blank');
})

// function delete_category(id){
// 	bootbox.confirm("Are you sure you want to delete this category?", function(result) {
// 		if(result) {
// 			dataSend = 'delete_category='+id;
// 			$.ajax({
// 				type: "POST",
// 				url: server_path+"wizard/libs/generate-shop_ajax.php",
// 				data: dataSend,
// 					// dataType:'json',
// 					success: function(data){						
// 						oTableCategories.fnDeleteRow(
// 							oTableCategories.fnGetPosition(
// 								document.getElementById('category_'+id)));  
// 					}
// 				});
// 		}
// 	});
// }
// function populate_category(id,lang){	
// 	// open_spiner();
// 	dataSend = 'populate_category='+id;
// 	$.ajax({
// 		type: "POST",
// 		url: server_path+"wizard/libs/generate-shop_ajax.php",
// 		data: dataSend,
// 		dataType:'json',
// 		success: function(data){
// 			alert(data);
// 					// close_spiner();							
// 					category_id = data[0]['id'];			
// 					$.each(data, function( key, value ) {
						
// 							$.each(value, function( val_key, val_value ) {

// 								if($("#"+val_key).is('div')){

// 									$("#"+val_key).html(val_value);
// 								}else{
// 									$("#"+val_key).val(val_value);
// 								}

// 							});
						
// 					});

// 					if(lang!=undefined){
// 						$("#lng_"+lang+' a').trigger('click');
// 					}
// 				}
// 		});
// }

// function save_category(){
// 	open_spiner();
// 	if(category_id>0){
// 		dataSend = 'save_category='+category_id;
// 	}else{
// 		dataSend = 'add_category=1';
// 	}
// 	dataSend=$('#categories_edit form').serialize()+'&'+dataSend;
	
// 	$.ajax({
// 		type: "POST",
// 		url: server_path+"wizard/libs/generate-shop_ajax.php",
// 		data: dataSend,
// 		dataType:'json',		
// 		success: function(data){
// 					close_spiner();
// 					if(category_id>0){
// 						$.each(data , function(key,value){
// 							alert(key)
// 							$("tr#category_"+category_id+" td:eq("+key+")").html(value);
// 						});
// 						bootbox.alert("Data has been saved.");
// 					}else{

// 					}

					

// 				}
// 		});
// }
// $(".item img").mouseenter(function(){
// 	$(this).css('border','1px solid #9585BF');
// });
// $(".item img").mouseleave(function(){
// 	$(this).css('border','0');
// });
$(".item img").on('click',function(){
	$(this).parent().parent().parent().find('img').css('border','0')
	$(this).css('border','6px solid #87B87F ');
	theme = $(this).attr('alt');
	button = $(this).parent().find('button:first');
	select_theme(theme,button);
});
//select theme funtion 
function select_theme(theme,butt){
	selected_theme=theme;

	//unselect all the buttons
	selected=$("#owl-pick .btn-success");
	$(selected).children('i').removeClass('icon-check').addClass('icon-check-empty');
	$(selected).children('span').html('Unselected');
	$(selected).addClass('btn-grey').removeClass('btn-success');
	//make theme selected button
	$(butt).removeClass('btn-grey').addClass('btn-success');
	$(butt).children('i').removeClass('icon-check-empty').addClass('icon-check');
	$(butt).children('span').html('Selected');
}

//preview theme function
///DE INTREBAT P ALPI
function preview_custom(){

	url =server_path_shop;
	window.open(url,'_blank');
}

function select_color_scheme(theme,butt){
	$('#custom_color_scheme button:eq(0)').removeClass('btn-success').addClass('btn-grey');
	$('.selected_color_scheme').removeClass('selected_color_scheme');
	selected_color_scheme = theme;
	selected=$("#color_scheme_wrapper .btn-success");
	$(selected).children('i').removeClass('icon-check').addClass('icon-check-empty');
	$(selected).children('span').html('Unselected');
	$(selected).addClass('btn-grey').removeClass('btn-success');
	//make theme selected button
	$(butt).parent().addClass('selected_color_scheme');
	$(butt).removeClass('btn-grey').addClass('btn-success');
	$(butt).children('i').removeClass('icon-check-empty').addClass('icon-check');
	$(butt).children('span').html('Selected');
}
function preview_theme(string){
	colors=string.split(',')
	url ="http://www.shop.neo-flux.com/?background="+colors[0]+'&main-color='+colors[1]+'&body-font-color='+colors[2]+'&menu-and-title-bg='+colors[3]+'&alt-header-color='+colors[4]+'&body-link-color='+colors[5]+'&menu-link-color='+colors[6]+'&footer-and-breadcrumbs='+colors[7];
	window.open(url,'_blank');
}


// for google localization
$("#open_map").on('click',function(){
	open_spiner();
	string_add = $("#address").val().replace(' ','+');
	string_city = $("#city").val().replace(' ','+');
	string_country=$('#state').val().replace(' ','+');
	string='http://maps.googleapis.com/maps/api/geocode/json?address='+string_add+','+string_city+','+string_country+'&sensor=true';
	
	$.ajax({
		type: "GET",
		url: string,
		dataType:'json',
		success: function(data){
			if(data.status=='OK'){
				var lat= data.results[0].geometry.location.lat;
				var lng=data.results[0].geometry.location.lng;
				setTimeout(function(){
				    mapLocation=new google.maps.LatLng(lat, lng),
				    map.setOptions({
				        center: mapLocation,
				        zoom: 20
				    });
				    google.maps.event.trigger(map,'resize');
				   placeMarker(mapLocation);
				    close_spiner();
				},800);
			}
		}
	});
	

});
function save_custom_color_sche(){
	string_custom_colors='';
	i=0;
	$('#modal-color_scheme input[type=text]').each(function(){
		text = this.value.replace('#', '');
		string_custom_colors=string_custom_colors+text+',';
		$('#custom_color_scheme .color_square:eq('+i+')').css('background',this.value);
		i++;
	})
	$('#custom_color_scheme').show();
	select_color_scheme('custom_color_scheme',$('#custom_color_scheme button:eq(0)'));
}
function send_checkbox(id){
	if($("#"+id).is(":checked")){
		send_data = 'change_checkbox=1&'+id+'=1';
	}else{
		send_data = 'change_checkbox=1&'+id+'=0';
	}

	$.ajax({
		type: "POST",
		url: server_path+'libs/generate-shop_ajax.php',
		dataType:'json',
		data:send_data,
		success: function(data){

		}
	});
}
function send_pr_nr(nr_prod){
	send_data='save_nr_prod='+nr_prod;
	$.ajax({
		type: "POST",
		url: server_path+'libs/generate-shop_ajax.php',
		dataType:'json',
		data:send_data,
		success: function(data){

		}
	});
}

function save_radio(id){	

	val = $("input[type=radio][name="+id+"]").val();

	

	dataString = 'save_radio=1+&'+id+'='+val
	$.ajax({
		type: "POST",
		url: server_path+'libs/generate-shop_ajax.php',		
		data:dataString,
		success: function(data){

		}
	});
}
function save_input(id){
	val = $("#"+id).val();
	dataString = 'save_input=1+&'+id+'='+val;
	$.ajax({
		type: "POST",
		url: server_path+'libs/generate-shop_ajax.php',		
		data:dataString,
		success: function(data){

		}
	});
}
function send_currency(val){
	
	dataString = 'save_currency='+val;
	$.ajax({
		type: "POST",
		url: server_path+'libs/generate-shop_ajax.php',		
		data:dataString,
		success: function(data){

		}
	});
}
